package uk.co.aetherworks.osc_messaging;

/*
 * Ped-ome
 *
 * MonomeCmdInterpreter - Interprets SerialOSC commands received from a monome
 *
 * Joe Handford aka Knecht 2011
 *
 */ 

// OSC Include Files
import com.illposed.osc.OSCPortOut;
import com.illposed.osc.OSCPortIn;
import com.illposed.osc.OSCListener;
import com.illposed.osc.OSCMessage;

// Java Net Include Files

import java.net.InetAddress;
import java.net.SocketException;
import java.net.UnknownHostException;

// aetherworks imports
import uk.co.aetherworks.debug.*;

public class MonomeCmdInterpreter extends Debuggable implements OSCListener {

	// The object that will forward the command to the app
	PedToApp forwarder;
	MonCmdListener myOwner;
	OSCCmdHandler cmd_processor;
	String monomePrefix = "";
	String appPrefix = "/pedome";
	
	public MonomeCmdInterpreter(MonCmdListener owner, OSCCmdHandler handler){
		myOwner = owner;
		cmd_processor = handler;
	}
	
	public void acceptMessage(java.util.Date time, OSCMessage message){
		DEBUG("MonToPed received message from Monome");
		
		String prefix, id;
		String address = message.getAddress();
		Object myArgs[] = message.getArguments();
		
		if ("/sys/port".equals(address)) {
			// Get monome port from message
			int port = ((Integer) myArgs[0]).intValue();
			DEBUG("received monome tx port: " + port);
		}
		else if ("/sys/prefix".equals(address)) {
			// Get monome prefix from message
			this.monomePrefix = ((String) myArgs[0]).toString();
			DEBUG("received monome prefix: " + this.monomePrefix);
			cmd_processor.monToPedPostProcessing(this.monomePrefix);
		}
		else if ("/sys/id".equals(address)) {
			// Get monome id from message
			id = ((String) myArgs[0]).toString();
			DEBUG("received monome id: " + id);
			//cmd_processor.setCmdListeningPort(app_listening_port);
		}
		else if ((monomePrefix + "/grid/key").equals(address)) {
			int x = ((Integer) myArgs[0]).intValue();
			int y = ((Integer) myArgs[1]).intValue();
			int state = ((Integer) myArgs[2]).intValue();
			DEBUG("received " + address + " " + x + " " + y + " " + state);
			message.setAddress(appPrefix + "/grid/key");
			forwarder.fwdMsg(message);
		}
		else if ((monomePrefix + "/tilt").equals(address)) {
			DEBUG("received /tilt");
			message.setAddress(appPrefix + "/tilt");
			forwarder.fwdMsg(message);
		}
	}
	
	public void attachForwarder(PedToApp aForwarder) {
		DEBUG("Attaching PedToApp as forwarder...");
		forwarder = aForwarder;
		myOwner.updateListeners(this.monomePrefix);
	}
	
	public void detachForwarder() {
		forwarder = null;
	}
	
	public void setAppPrefix(String prefix) {
		appPrefix = prefix;
	}
}
